/**
 * Created by yuweimei on 2018/3/25.
 */
app.controller('release', function($scope, $http) {
	$('.top_two_tips ul li').click(function() {
		console.log(1);
		$(this).siblings(".click_div").removeClass("click_div");
		$(this).addClass("click_div");

	});
	var token = localStorage.getItem('token');
	// 准备工作
	if(!app.isPlusReady || !app.addressInfo) {
		$.alert('不能获取到当前位置，无法发布订单');
		$scope.positionX = 30.58178;
		$scope.positionY = 104.277946;
	}
	if(app.isPlusReady) {
		$scope.positionX = app.addressInfo.coords.latitude;
		$scope.positionY = app.addressInfo.coords.longitude;
		$scope.addressDetail = app.addressInfo.addresses;
	}
	$scope.tourDynamics = {};
	$scope.addTour = function() {
		//判断有无证书
		if(!token) {
			$.toast('请先登录');
			location.href = '#login';
			return;
		}
		var dynamicImgString = "";
		//判断是否上传有图片
		if($scope.dynamicImgList.length > 0) {
			//按规则将图片数组转化为string
			for(var i = 0; i < $scope.dynamicImgList.length; i++) {
				if(i == $scope.dynamicImgList.length - 1) {
					dynamicImgString = dynamicImgString + $scope.dynamicImgList[i];
				} else {
					dynamicImgString = dynamicImgString + $scope.dynamicImgList[i] + ',';
				}
			}
		}
		var tourDynamics = {
			placeFrom: $scope.tourDynamics.goWhere,
			placeTo: $scope.tourDynamics.toWhere,
			tourdynaOutTime: new Date($scope.tourDynamics.toDate).getTime(),
			tourdynaContent: $scope.tourDynamics.toTrip,
			tourdynaImg: dynamicImgString,
			contactway: $scope.tourDynamics.phone,
			tourdynaType: $scope.type
		};
		if(undefined == $scope.tourDynamics.goWhere || undefined == $scope.tourDynamics.toWhere || undefined == $scope.tourDynamics.toDate || undefined == $scope.tourDynamics.toTrip || undefined == $scope.tourDynamics.phone || undefined == $scope.type) {
			$.toast("请完善订单信息！");
		} else {
			console.log(tourDynamics);
			//发送POST请求
			$http({

				method: 'post',
				url: app.netPath + "/dynamic/details/add",
				headers: {
					'Authorization': token
				},
				data: tourDynamics,
				params: {
					positionX: $scope.positionX,
					positionY: $scope.positionY
				}

			}).then(function(res) {
				if(!res.data.error) {
					console.log(res.data.data);
					$.toast(res.data.msg);

					for(var i = 0; i < res.data.data.length; i++) {
						if(res.data.data[i].user.userAvatarAddress) {
							res.data.data[i].user.userAvatarAddress = app.netPath + '/resources/img/' + res.data.data[i].user.userAvatarAddress;
							app.buildImageUrl(res.data.data[i].user, 'userAvatarAddress', function() {
								$scope.$digest();
							});
						}
						var lat = res.data.data[i].positionX;
						var lng = res.data.data[i].positionY;
						res.data.data[i].distance = app.getGreatCircleDistance(lat, lng);
						if(res.data.data[i].distance >= 1000) {
							res.data.data[i].distance = (app.getGreatCircleDistance(lat, lng) / 1000).toFixed(2) + "千米";
						} else {
							res.data.data[i].distance = app.getGreatCircleDistance(lat, lng) + "米";
						}
					}
					app.tuijieList = res.data.data;
					location.href = '#release_success';
				} else {
					$.toast(res.data.msg);
				}

			});

		}
	};
	// 定义集合存储动态上传图片
	$scope.dynamicImgList = [];
	$scope.dynamicImg = '';
	//单次提交图片的函数
	//参数为传入的一个文件类型input
	$scope.img_upload = function(files) {

		console.log('ready to upload img.');

		if(!token) {
			$.toast('请先登录');
			return;
		}

		if(!files || !files[0]) {
			console.log('文件为空');

			return;
		}

		//规定上传到服务器图片的大小
		var needHeight = 300;
		var needWidth = 300;

		//规定略缩图大小
		var smallWidth = needWidth * 0.33;

		//FileReader用来读取本地文件
		var reader = new FileReader();

		//实例化图片用于被加载在画布上
		var img = new Image();

		// 破除一个协议
		img.setAttribute("crossOrigin", 'Anonymous');

		//声明一个画布对象，当图片上传成功后添加到数组中便于显示
		var img_obj = {};

		//获取当前时间戳作为画布唯一id
		img_obj.id = new Date().getTime();

		//自动刷新双向绑定，预防双向绑定失效
		$scope.$digest();

		//获取预览画布
		var canvas = document.createElement('canvas');
		canvas.width = needWidth;
		canvas.height = needHeight;

		//控制略缩图大小
		canvas.style.width = smallWidth + 'px';

		var ctx = canvas.getContext("2d");

		//当图片加载完毕执行动作
		reader.onload = function() {

			// 通过 reader.result 来访问生成的 DataURL
			img.src = reader.result;

			img.onload = function() {

				//获取图片的高宽
				var width = img.width;
				var height = img.height;

				//获取需要使用的矩形图片区域
				var real_width = width * needHeight / needWidth > height ? height * needWidth / needHeight : width;
				var real_height = width > height * needWidth / needHeight ? height : width * needHeight / needWidth;

				//console.log('need:'+real_width+' '+real_height);
				//console.log('real:'+width+' '+height);

				//定位使图片居中
				var img_x = (width - real_width) / 2;
				var img_y = (height - real_height) / 2;

				//在画布上渲染头像预览
				ctx.drawImage(img, img_x, img_y, real_width, real_height, 0, 0, needWidth, needHeight);

				//将画布渲染的图像转换为base64字符串储存在data中
				var data = canvas.toDataURL();
				// console.log(data);

				//发送POST请求
				$http({

					method: 'post',
					url: app.netPath + "/dynamic/details/image-upload",
					headers: {
						'Authorization': token
					},
					data: data

				}).then(function(res) {
					console.log(res.data);

					if(!res.data.error) {
						console.log(res.data.data);
						//封装路径显示图片
						$scope.dynamicImg = app.netPath + '/resources/taskImg/' + res.data.data;
						//当图片上传成功添加图片显示节点
						$("#img-list").append("<div class='img_div'><img src='" + $scope.dynamicImg + "'></div>");
						//存入刚上传成功的图片名称
						$scope.dynamicImgList.push(res.data.data);
						//监听点击事件（移除不想上传的图片节点）
						$('.img_div').bind('click', function() {
							//得到当前点击的图片节点位于集合中的顺序
							var i = $(this).index();
							$('.img_div')[i].remove();
							//相应图片数组中取出想应值
							$scope.dynamicImgList.splice(i, 1);
							console.log($scope.dynamicImgList);
						})
					} else {
						$.toast('错误代码：' + res.data.error + "," + res.data.msg);
					}

				}, function() {
					$scope.img_del(index);
					$.toast('网络或设置错误');
				});
				//清除原来画布内容
				ctx.clearRect(0, 0, needWidth, needHeight);
			};

		};
		//加载选中的图片
		reader.readAsDataURL(files[0]);
	};
	$scope.type = 1;
	$scope.setType = function(index) {
		$scope.type = index;
	}
});